package brackets

import (
	"errors"
	"regexp"
	"strings"
)

const testVersion = 5

var BracketError = errors.New("BracketError")
var BracketReg = regexp.MustCompile(`[{|\[|(|)|\]|}]+`)

// Bracket
// {[()]} = [123 91 40 41 93 125]
func Bracket(input string) (r bool, err error) {
	input = strings.Join(BracketReg.FindAllString(input, -1), "")
	runes := []rune(input)

	brackets := []rune{}
	for i := 0; i < len(runes); i++ {
		if runes[i] == 123 || runes[i] == 91 || runes[i] == 40 {
			brackets = append(brackets, runes[i])
			continue
		}

		if len(brackets) == 0 {
			continue
		}

		last := brackets[len(brackets)-1]
		if runes[i] == last+2 || runes[i] == last+1 {
			brackets = brackets[0 : len(brackets)-1]
			continue
		}

		brackets = append(brackets, runes[i])
	}

	if len(brackets) == 0 {
		r = true
	}

	return
}
